package com.sloth.bear.util;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.List;

/**
 * 文件工具类
 */
public class FileUtils {
    
    private static final List<String> VIDEO_EXTENSIONS = Arrays.asList(
        "mp4", "avi", "mkv", "mov", "wmv", "flv", "webm", "m4v", "3gp", "mpg", "mpeg"
    );
    
    /**
     * 获取文件扩展名
     */
    public static String getFileExtension(String fileName) {
        if (fileName == null || !fileName.contains(".")) {
            return "";
        }
        return fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
    }
    
    /**
     * 判断是否为视频文件
     */
    public static boolean isVideoFile(String fileName) {
        String extension = getFileExtension(fileName);
        return VIDEO_EXTENSIONS.contains(extension);
    }
    
    /**
     * 判断文件是否符合扫描条件
     */
    public static boolean isValidFile(String fileName, long fileSize, long threshold, List<String> supportedFormats) {
        // 检查文件大小
        if (fileSize < threshold) {
            return false;
        }
        
        // 检查文件格式
        String extension = getFileExtension(fileName);
        return supportedFormats.contains(extension);
    }
    
    /**
     * 格式化文件大小为可读格式
     */
    public static String formatFileSize(long size) {
        if (size <= 0) return "0 B";
        
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }
    
    /**
     * 获取文件目录路径
     */
    public static String getDirectory(String filePath) {
        if (filePath == null) return "";
        
        int lastSeparatorIndex = filePath.lastIndexOf("/");
        if (lastSeparatorIndex == -1) {
            lastSeparatorIndex = filePath.lastIndexOf("\\");
        }
        
        return lastSeparatorIndex > 0 ? filePath.substring(0, lastSeparatorIndex) : "";
    }
}